package com.buaa.aimall.authModule.controller;

import com.buaa.aimall.authModule.dto.TokenDTO;
import com.buaa.aimall.authModule.dto.UserIdentityDTO;
import com.buaa.aimall.authModule.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Token控制器
 * 提供生成token和验证token的接口
 */
@RestController
@RequestMapping("/api/auth")
public class TokenController {

    private final TokenService tokenService;

    @Autowired
    public TokenController(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    /**
     * 根据用户ID生成token
     * @param requestBody 包含userId的请求体
     * @return 包含token的响应
     */
    @PostMapping("/token")
    public ResponseEntity<TokenDTO> generateToken(@RequestBody Map<String, String> requestBody) {
        String userId = requestBody.get("userId");
        System.out.println("开始生成token，用户ID: " + userId);
        try {
            String token = tokenService.generateToken(userId);
            System.out.println("token生成成功");
            return ResponseEntity.ok(new TokenDTO(token));
        } catch (Exception e) {
            System.out.println("生成token时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e; // 异常会被全局异常处理器捕获
        }
    }

    /**
     * 验证token并返回用户身份信息
     * @param requestBody 包含token的请求体
     * @return 用户身份信息
     */
    @PostMapping("/verify")
    public ResponseEntity<UserIdentityDTO> verifyToken(@RequestBody Map<String, String> requestBody) {
        String token = requestBody.get("token");
        System.out.println("开始验证token");
        try {
            UserIdentityDTO userIdentity = tokenService.verifyToken(token);
            System.out.println("token验证成功，用户ID: " + userIdentity.getUserId());
            return ResponseEntity.ok(userIdentity);
        } catch (Exception e) {
            System.out.println("验证token时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e; // 异常会被全局异常处理器捕获
        }
    }
} 